<?php

namespace App\Http\Controllers\VideoApi;

use App\Http\Config\ErrorCode;
use App\Library\UpTools;
use App\Models\video\CommonServer;
use App\Models\video\CourseCatalogModel;
use App\Models\video\CourseModel;
use App\Models\video\VideoSettingModel;
use App\Models\video\VodVideoModel;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class CourseController extends BaseController
{
    private $field = [
        "name" => "require", "brief" => "require", "description" => "", "pay_mode" => 0, "pay_money" => "", "member_mode" => "0", "status" => "1",
        "cover_img_id" => "require", "number" => 0
    ]; // 填入数据库需要存储的表字段
    private $fieldMsg = [
        "name" => "课程名", "cover_img_id" => "封面图", 'brief' => "简介"
    ];
    private $data = [];
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    // 获取可用的所有课程
    public function getAllCourse(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$broadcasterId = CommonServer::judgeUpIdentity($request->userLoginData["id"], $request->mallData["id"])){
            return $this->return_result(ErrorCode::code("customized", "用户不是UP主"));
        }
        $subSql = CourseCatalogModel::query()->whereRaw("course_id = ".CourseModel::query()->getModel()->getTable().".id")
            ->selectRaw("count(*)")->toSql();
        $data = CourseModel::query()->select("id", "name", "number", 'pay_mode')
            ->selectRaw("({$subSql}) as currentNum")
            ->where(["mall_id" => $request->mallData["id"], "status" => 1, "broadcaster_id" => $broadcasterId])
            ->get()->toArray();
        $data = UpTools::transferFields($data);
        foreach ($data as $key => $item){
            if($item["currentNum"] >= $item["number"]){
                unset($data[$key]);
            }
        }
        $this->returnData["data"] = array_values($data);
        return $this->return_result($this->returnData);
    }

    // 获取UP主的课程列表
    public function getUpCourseList(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        $page = $request->page ?: 1;
        $pageSize = $request->pageSize ?: 10;
        if(!$broadcasterId = CommonServer::judgeUpIdentity($request->userLoginData["id"], $request->mallData["id"])){
            return $this->return_result(ErrorCode::code("customized", "用户不是UP主"));
        }
        $data = CourseModel::getList("id,name,cover_img_id,view_count,created_at,number", ["mall_id" => $request->mallData["id"], "broadcaster_id" => $broadcasterId], $page, $pageSize);
        foreach ($data['list'] as &$item){
            $item["currentNum"] = CourseCatalogModel::query()->where(["course_id" => $item["id"]])->count();
        }
        $this->returnData["data"] = $data;
        return $this->return_result($this->returnData);
    }

    // 课程详情
    public function getCourseInfo(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", "课程ID"));
        }
        if(!$broadcasterId = CommonServer::judgeUpIdentity($request->userLoginData["id"], $request->mallData["id"])){
            return $this->return_result(ErrorCode::code("customized", "用户不是UP主"));
        }
        $data = CourseModel::getFields("*", ["id" => $request->id, "broadcaster_id" => $broadcasterId]);
        if(!empty($data)){
            if($data["payMoney"] == "0"){
                $data["memberPayMoney"] = $data["payMoney"] = 0;
            }elseif($data["payMoney"] == "2"){ // 会员免费
                $data["memberPayMoney"] = 0;
            }else{ // 付费
                if($data["memberMode"] == '0') {
                    $data["memberPayMoney"] = 0;
                }else{
                    $data["memberPayMoney"] = $data["payMoney"];
                    $settingData = VideoSettingModel::getFields("open_member,member_discount", ["mall_id" => request()->mallData["id"]], true, false);
                    if($settingData["openMember"] == '1' && !empty($settingData["memberDiscount"])) {
                        $data["memberPayMoney"] = sprintf('%.2f', $data["payMoney"] * $settingData["memberDiscount"] / 100);
                    }
                }
            }
            $data["currentNum"] = CourseCatalogModel::query()->where(["course_id" => $data["id"]])->count();
        }
        $this->returnData["data"] = $data;
        return $this->return_result($this->returnData);
    }

    // 获取课程目录列表
    public function getCourseCatalogList(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", "课程ID"));
        }
        if(!$broadcasterId = CommonServer::judgeUpIdentity($request->userLoginData["id"], $request->mallData["id"])){
            return $this->return_result(ErrorCode::code("customized", "用户不是UP主"));
        }
        $page = $request->page ?: 1;
        $pageSize = $request->pageSize ?: 10;
        $db = CourseCatalogModel::query()->from(CourseCatalogModel::query()->getModel()->getTable()." as cc")
            ->leftJoin(VodVideoModel::query()->getModel()->getTable()." as v", "v.id", "=", "cc.video_id")
            ->where(["cc.course_id" => $request->id]);
        $data['count'] = $db->count();
        $data['currentPage'] = $page;
        $data['totalPage'] = ceil(($data['count'])/$pageSize);
        $data["list"] = $db->select(["v.id","v.title","v.cover_img_id","v.desc","v.view_count","v.video_length",'v.create_time'])
            ->skip(($page - 1) * $pageSize)->take($pageSize)->orderBy("cc.created_at", "asc")
            ->get()->toArray();
        if(!empty($data["list"])){
            $data["list"] = VodVideoModel::transferField($data["list"]);
            foreach ($data["list"] as &$item){
                $item["createTime"] = substr($item["createTime"], 0, 10);
            }
        }
        $this->returnData["data"] = $data;
        return $this->return_result($this->returnData);
    }

    // 删除目录
    public function delCourseCatalog(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", "课程ID"));
        }
        if(!$request->videoId){
            return $this->return_result(ErrorCode::code("params_not_exist", "课程视频ID"));
        }
        if(!$broadcasterId = CommonServer::judgeUpIdentity($request->userLoginData["id"], $request->mallData["id"])){
            return $this->return_result(ErrorCode::code("customized", "用户不是UP主"));
        }
        CourseCatalogModel::delByFilter(["video_id" => $request->videoId, 'course_id' => $request->id]);
        return $this->return_result($this->returnData);
    }

    // 添加课程
    public function toAddCourse(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$broadcasterId = CommonServer::judgeUpIdentity($request->userLoginData["id"], $request->mallData["id"])){
            return $this->return_result(ErrorCode::code("customized", "用户不是UP主"));
        }
        foreach ($this->field as $k => $v) {
            $ks = Str::camel($k); //转换字段，变驼峰
            if($v === 'require' && !$request->$ks){
                return ErrorCode::code("params_not_exist", $this->fieldMsg[$k]);
            }
            $this->data[$k] = $request->$ks ? trim($request->$ks) : $v;
        }
        $this->data["broadcaster_id"] = $broadcasterId;
        CourseModel::toAdd($this->data);
        return $this->return_result($this->returnData);
    }

    // 更新课程
    public function toUpdateCourse(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", "课程ID"));
        }
        if(!$broadcasterId = CommonServer::judgeUpIdentity($request->userLoginData["id"], $request->mallData["id"])){
            return $this->return_result(ErrorCode::code("customized", "用户不是UP主"));
        }
        foreach ($this->field as $k => $v) {
            $ks = Str::camel($k); //转换字段，变驼峰
            if($v === 'require' && !$request->$ks){
                return ErrorCode::code("params_not_exist", $this->fieldMsg[$k]);
            }
            if($request->$ks) {
                $this->data[$k] = trim($request->$ks);
            }
        }
        $catalogCount = CourseCatalogModel::query()->where("course_id", $request->id)->count();
        if($catalogCount > $this->data['number']){
            return $this->return_result(ErrorCode::code("customized", "课程期数不能小于{$catalogCount}"));
        }
        CourseModel::doUpdate($this->data, ["id" => $request->id, "broadcaster_id" => $broadcasterId]);
        return $this->return_result($this->returnData);
    }

    // 删除课程
    public function delCourse(Request $request){
        if($this->returnData["code"] !== 0){
            return $this->return_result($this->returnData);
        }
        if(!$request->id){
            return $this->return_result(ErrorCode::code("params_not_exist", "课程ID"));
        }
        if(!$broadcasterId = CommonServer::judgeUpIdentity($request->userLoginData["id"], $request->mallData["id"])){
            return $this->return_result(ErrorCode::code("customized", "用户不是UP主"));
        }
        CourseModel::delByFilter(["id" => $request->id, "broadcaster_id" => $broadcasterId]);
        return $this->return_result($this->returnData);
    }
}
